package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.PurchaseStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author atguigu-mqx
 * @ClassName TrackPurchaseStrategy
 * @description: TODO
 * @date 2024年04月29日
 * @version: 1.0
 */
@Service("1002")
@Slf4j
public class TrackPurchaseStrategy implements PurchaseStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Override
    public void purchase(UserPaidRecordVo userPaidRecordVo) {
        //	购买声音. user_paid_track
        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(wrapper);
        if (count > 0) {
            //  记录日志
            log.info("当前用户{} 已购买过声音Id,对应的订单编号{}", userPaidRecordVo.getUserId(), userPaidRecordVo.getOrderNo());
            return;
        }
        //  获取专辑Id,声音对象中有专辑Id.
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0));
        Assert.notNull(trackInfoResult, "返回声音结果集为空");
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo, "声音对象为空");
        //  存储数据. 循环遍历
        for (Long trackId : userPaidRecordVo.getItemIdList()) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            //  赋值：
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(trackId);
            this.userPaidTrackMapper.insert(userPaidTrack);
        }
    }
}
